//
//  TextView.swift
//  CodeView
//
//  Created by qi long chen on 2021/9/9.
//

import UIKit

class ZYTextView: UIView {

    var text: UILabel!
    private var line: UIView!
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }
    
    private func setUI(){
        
        self.layer.cornerRadius = 8
        self.layer.borderWidth = 1
        self.layer.borderColor = UIColor.lightGray.cgColor
        
        text = UILabel(frame: self.bounds)
        text.textAlignment = .center
        addSubview(text)
        
        line = UIView(frame: CGRect(x: (self.bounds.width - 2)/2, y: 0.25*self.bounds.height, width: 2, height: 0.5*self.bounds.height))
        line.backgroundColor = .red
        addSubview(line)
        line.alpha = 0
    }

    private func animation() -> CABasicAnimation {
        
        let basicAnimation = CABasicAnimation(keyPath: "opacity")
        basicAnimation.fromValue = 1
        basicAnimation.toValue = 0
        basicAnimation.duration = 0.5
        basicAnimation.autoreverses = true
        basicAnimation.fillMode = .forwards
        basicAnimation.repeatCount = .greatestFiniteMagnitude
        basicAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        return basicAnimation
    }
    
    func showAnimation() {
        
        self.line.alpha = 1
        if (self.line.layer.animation(forKey: "link") == nil) {
            self.line.layer.add(animation(), forKey: "link")
        }
    }
    
    func hiddenAnimation() {

        self.line.alpha = 0
        self.line.layer.removeAllAnimations()
    }
}
